package com.example.demo.service;

import com.example.demo.compile.Answer;
import com.example.demo.dao.mapper.AcMapper;
import com.example.demo.dao.mapper.ProblemMapper;
import com.example.demo.dao.pojo.AcInfo;
import com.example.demo.dao.pojo.ProblemInfo;
import com.example.demo.dao.pojo.UserInfo;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class ThreadService {

    /**
     * 更新题目提交后的次数
     * 期望在线程池中进行，不会影响主线程
     * @param problemMapper
     * @param problemInfo
     * @param answer
     */
    @Async("taskExecutor")
    public void updateProblemVisitCount(ProblemMapper problemMapper, ProblemInfo problemInfo, Answer answer) {
        int id = problemInfo.getId();
        int visitCount = problemInfo.getVisitCount();
        int acCount = problemInfo.getAcCount();
        if(answer.getError() == 0){
            // 编译运行成功，即 visit 和 ac 次数都 + 1
            problemMapper.updateCount(id, visitCount, acCount, 1, 1);
        }else{
            problemMapper.updateCount(id, visitCount, acCount, 1, 0);
        }
    }

    /**
     * 更新当前用户与该题的状态
     * @param acMapper
     * @param userInfo
     * @param problemInfo
     * @param answer
     */
    @Async("taskExecutor")
    public void updateAc(AcMapper acMapper, UserInfo userInfo, ProblemInfo problemInfo, Answer answer) {
        int id = problemInfo.getId();
        int uid = userInfo.getId();
        if(answer.getError() == 0){
            // 编译运行成功，则将该题和用户绑定
            AcInfo acInfo = acMapper.selectOne(id, uid);
            if(acInfo == null){
                acMapper.add(id, uid);
            }
        }
    }
}
